package cn.itcast.nems.manager.eca;

import cn.itcast.nems.manager.kc.KeyCloakManager;
import cn.itcast.nems.manager.util.OkHttpUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 调用ECA相关接口  ，如：获取合同链接
 * </p>
 *
 * @author zhouwei
 * @since 2024/4/12 11:28 AM
 **/
public class ECAManager {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final ObjectMapper objectMapper;
    private final KeyCloakManager keyCloakManager;
    private final String ecaDomain;
    private final String sysClientId ;
    private final String dataScope ;

    public String convertContractStatus(String contractStatus) {
        String  status  = "previewed"  ;
        if( Objects.nonNull(contractStatus)) {
            status = switch (contractStatus.toLowerCase()) {
                case "previewed" -> "previewed";
                case "signed" -> "signed";
                case "canceled" -> "canceled";
                default -> "previewed";
            };
        }
        return  status ;
    }
    public ECAManager(String ecamDomain, KeyCloakManager keyCloakManager, String sysClientId, String dataScope) {
        logger.info("ECAManager init with ecamDomain: {} ", ecamDomain);
        this.keyCloakManager = keyCloakManager;
        this.ecaDomain = ecamDomain.endsWith("/") ? ecamDomain : ecamDomain + "/";
        this.sysClientId = sysClientId ;
        this.dataScope = dataScope ;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * <p>
     * 根据合同编号获取合同链接
     * </p>
     *
     * @param  contractNo 合同编号
     * @param contractStatus 合同状态
     * @author zhouwei
     * @since 2024/4/12 11:32 AM
     **/
    public String getContractUrl(String contractNo, String contractStatus) throws Exception {
        String url = String.format(this.ecaDomain + "contracts/url?bizContractNo=%s&status=%s",
                URLEncoder.encode(contractNo, StandardCharsets.UTF_8), contractStatus);
        String token = this.keyCloakManager.getKeyCloakAccessToken();
        Map<String, String> headMap = Map.of(
                "Content-Type", "application/json",
                "Authorization", "Bearer " + token,
                "timestamp", String.valueOf(System.currentTimeMillis()) ,
                "noncestr", UUID.randomUUID().toString().replaceAll("-", ""),
                "sysClientId", sysClientId,
                "dataScope", dataScope
        ) ;
        final String response = OkHttpUtil.doGet(url,headMap);
        logger.info("get contract url contractNo： {} ，contractStatus：{} response:{}", contractNo, contractStatus, response);
        if (StringUtils.hasText(response)) {
            final JsonNode res = objectMapper.readTree(response);
            return res.path("url").asText();
        }
        return null;
    }

}
